package com.atsmart.app.activity;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.ReportListAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.TaskPageInfo;

import com.atsmart.app.model.TemplateInfo;
import com.atsmart.app.model.TemplateListInfo;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.sql.TaskInfoSqlHelper;
import com.atsmart.app.sql.TaskNumSqlHelper;
import com.atsmart.app.sql.TemplateInfoSql;

import com.atsmart.app.sql.TempFromTaskSql;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;

public class ReportListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler,
		OnClickListener {
	private static final String TAG = ReportListActivity.class.getName();
	public static final int REPORT_TYPE_UNREPORT = 1;
	public static final int REPORT_TYPE_REPORTED = 2;

	private ListView listView;
	private TemplateListInfo datasource;
	private ReportListAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private int listType;
	private String taskTime;
	private String taskname;
	private static boolean asyntaskIsFinished = true;
	private Button refresh;
	private Button history;
	
 
	private TemplateInfoSql templateInfoSql = null;
	private TempFromTaskSql tesql = null;
	
	private NumberSqlHelper nsql = null;
	private int task_id = 0;
	private int type = 0;
	private TaskInfoSqlHelper tasksql = null;
	private TaskNumSqlHelper tnsql = null;
	private Context context;
	private boolean fromTaskList = false;
	private int isPage = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list_layout);
		
		context = this;
		
		refresh = (Button) findViewById(R.id.btn_refresh);
		history = (Button) findViewById(R.id.btn_history);
		history.setBackgroundResource(R.drawable.tab_task_press);
	
		templateInfoSql = new TemplateInfoSql();
		templateInfoSql.open(BizApp.getInstance().getSqlHelper());
		
		tesql = new TempFromTaskSql();
		tesql.open(BizApp.getInstance().getSqlHelper());
		
		tasksql = new TaskInfoSqlHelper();
		tasksql.open(BizApp.getInstance().getSqlHelper());
		tnsql = new TaskNumSqlHelper();
		tnsql.open(BizApp.getInstance().getSqlHelper());
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
		
		NumberResponseInfo ninfo = nsql.getNumberByType(3);
		
		if (ninfo == null || ninfo.getNumber() > 0) {
		} else {
			refresh.setVisibility(View.INVISIBLE);
		}
		Bundle bundle = getIntent().getExtras();
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int width = metrics.widthPixels;
		int height = metrics.heightPixels;
//		Log.e("TAG", "width: = " + width + " , hight: = " + height);
		/**** bundle != null 与任务相关联的汇报模板**/
		if (bundle != null) {
		 
			task_id = bundle.getInt(PersistentKeyUtil.TASK_ID, 0);
			type = bundle.getInt(PersistentKeyUtil.REPORT_TYPE, 0);
			taskTime = bundle.getString(PersistentKeyUtil.TASK_TIME);
			taskname = bundle.getString(PersistentKeyUtil.TASK_NAME);
 
		}
	
		if (task_id != 0) {
			fromTaskList = true;
		}
		
		/**********************按钮隐藏************************/
	 
		history.setVisibility(View.GONE);
		refresh.setVisibility(View.GONE);
		refresh.setOnClickListener(this);
		history.setOnClickListener(this);
		/****************************************************/
		
		BizApp.getInstance().showMemory();
		
		listType = getIntent().getIntExtra(ReportForAllActivity.REPORT_TYPE, 1);
		listView = (ListView) findViewById(R.id.listview);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> partent, View view,
					int position, long id) {
				if (listType == REPORT_TYPE_REPORTED) {
					return;
				}
				if (adapter == null) {
					return;
				}
				TemplateInfo templateInfo = (TemplateInfo) adapter
						.getItem(position);
				if (templateInfo == null) {
					return;
				}
				if (templateInfo.getUpdate_type() == 1) {
					return;
				}
				Bundle bundle = new Bundle();
				bundle.putInt(PersistentKeyUtil.REPORT_TYPE, type);
				bundle.putInt(PersistentKeyUtil.TASK_ID, task_id);
				bundle.putInt(PersistentKeyUtil.TEMPLATE_ID_STRING,
						templateInfo.getId());
				bundle.putInt(PersistentKeyUtil.LOCATION_FLG,
						templateInfo.getLocation_flag());
				bundle.putString(PersistentKeyUtil.TASK_TIME, taskTime);
				bundle.putString(PersistentKeyUtil.TASK_NAME, taskname);
				bundle.putString(PersistentKeyUtil.TEMPLATE_NAME,
						templateInfo.getName());
//				Log.e("TAG", "上传位置标志位： = " + templateInfo.getLocation_flag());
				bundle.putBoolean("isFromTask", fromTaskList);
				
				IntentUtil.redirectToNext(ReportListActivity.this,
						ReportActivity.class, bundle);
				 
			}
		});	
	}

	@Override
	protected void onResume() {
		//TODO
		super.onResume();

		if (fromTaskList) {
			int count = tesql.getCount(task_id);
			if (count > 0) {
				// Log.e("TAG", "from sql by taskList");
				isFromsql = true;
				if (asyntaskIsFinished) {
					pageIndex = 0;
					showLoading();
					getDataFromSQL();
					asyntaskIsFinished = false;
				}
			} else {
				isFromsql = false;
				if ((BizApp.getInstance().isWiFiActive() || BizApp
						.getInstance().isNetworkAvailable())
						&& BizApp.getInstance().keeping) {
					if (asyntaskIsFinished) {
						pageIndex = 0;
						showLoading();
						getData();
						asyntaskIsFinished = false;
					}
				}
			}
		} else {
			int count = templateInfoSql.getCount();
			if (count > 0) {
				// Log.e("TAG", "from sql by reportlist");
				isFromsql = true;
				if (asyntaskIsFinished) {
					pageIndex = 0;
					showLoading();
					getDataFromSQL();
					asyntaskIsFinished = false;
				}
			} else {
				isFromsql = false;
				if ((BizApp.getInstance().isWiFiActive() || BizApp
						.getInstance().isNetworkAvailable())
						&& BizApp.getInstance().keeping) {
					if (asyntaskIsFinished) {
						pageIndex = 0;
						showLoading();
						getData();
						asyntaskIsFinished = false;
					}
				}
			}
		}

	}

	private boolean isFromsql = false;

	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<TemplateListInfo>() {

			@Override
			protected TemplateListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				if (task_id == 0) {
					PageInfo pageInfo = new PageInfo();
					pageInfo.begin = pageIndex * pageSize + isPage;
					pageInfo.end = (pageIndex + 1) * pageSize + isPage;
					return ServiceHelper.getInstance()
							.postData(ServiceHost.getTemplateURL(),
									new Gson().toJson(pageInfo),
									TemplateListInfo.class);
				} else {
					TaskPageInfo pageInfo = new TaskPageInfo();
					pageInfo.begin = pageIndex * pageSize + isPage;
					pageInfo.end = (pageIndex + 1) * pageSize + isPage;
					pageInfo.id = task_id;
					CommonBody body = new CommonBody();
					body.setCommand(5);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					return ServiceHelper.getInstance()
							.postData(ServiceHost.getTemplateURL(),
									new Gson().toJson(body),
									new Gson().toJson(pageInfo),
									TemplateListInfo.class);
				}

			}

			@Override
			protected void runWithResult(TemplateListInfo result)
					throws Exception {
				if (result != null) {
					dealwithResult(result);
				}else{
					getDataFromSQL();
				}
				asyntaskIsFinished = true;
			
				hideLoading();
				finishedLoad(TAG);

			}

			@Override
			protected void runWithError(TemplateListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;
				hideLoading();
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					getDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}
	
	
	private void getDataByUrl2() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<TemplateListInfo>() {

			@Override
			protected TemplateListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				if (task_id == 0) {
					PageInfo pageInfo = new PageInfo();
					pageInfo.begin = pageIndex * pageSize + isPage;
					pageInfo.end = (pageIndex + 1) * pageSize + isPage;
					return ServiceHelper.getInstance()
							.postData(ServiceHost.getTemplateURL(),
									new Gson().toJson(pageInfo),
									TemplateListInfo.class);
				} else {
					TaskPageInfo pageInfo = new TaskPageInfo();
					pageInfo.begin = pageIndex * pageSize + isPage;
					pageInfo.end = (pageIndex + 1) * pageSize + isPage;
					pageInfo.id = task_id;
					CommonBody body = new CommonBody();
					body.setCommand(5);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					return ServiceHelper.getInstance()
							.postData(ServiceHost.getTemplateURL(),
									new Gson().toJson(body),
									new Gson().toJson(pageInfo),
									TemplateListInfo.class);
				}

			}

			@Override
			protected void runWithResult(TemplateListInfo result)
					throws Exception {
				if (result != null) {
					dealwithResult(result);
				}else{
					getDataFromSQL();
				}
				asyntaskIsFinished = true;
			
				hideLoading();
				finishedLoad(TAG);

			}

			@Override
			protected void runWithError(TemplateListInfo result, int iErrorCode)
					throws Exception {
	
				asyntaskIsFinished = true;
				getDataFromSQL();
				hideLoading();
			}
		}.execute();
	}
	
	private void dealwithResult(TemplateListInfo result) {
		
		datasource = result;
		if(fromTaskList){
			if (datasource != null && datasource.getTemplates() != null) {
				for(TemplateInfo info: datasource.getTemplates()){
					try{
						tesql.deleteAttribute(info.getId(), task_id);
					}catch (Exception e) {
					}
					tesql.addTemplateInfo(info, task_id);
				}
			}
		}else{
			if (datasource != null && datasource.getTemplates() != null) {
				for (TemplateInfo info : datasource.getTemplates()) {
					try {
						templateInfoSql.deleteAttribute(info.getId());
					} catch (Exception e) {
					}
					templateInfoSql.addTemplateInfo(info, info.getId());
				}
			}
		}
		for (TemplateInfo ti : datasource.getTemplates()) {
			List<Integer> k = tnsql.getTaskList1(task_id);
			if (k != null) {
				for (Integer tif : k) {
					if (Integer.valueOf(tif) == ti.getId()) {
						ti.setUpdate_type(1);
						break;
					}
				}
			}
		}
		bindData();
	}
	
	
	private void getDataFromSQL() {
//		Log.e("TAG", "sql size: = " + templateInfoSql.getCount());
	 
		new ServiceAsynTask<TemplateListInfo>() {

			@Override
			protected TemplateListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = pageIndex * pageSize;
				pageInfo.end = (pageIndex + 1) * pageSize;
				if(fromTaskList){
					datasource = tesql.getTemplateInfoByTaskId(task_id);
				}else{
					if(pageInfo.end >= templateInfoSql.getCount()){
						pageInfo.end = templateInfoSql.getCount();
					}
					datasource = templateInfoSql.getTemplateInfo(pageInfo.begin, pageInfo.end);
				}
				return datasource;
			}

			@Override
			protected void runWithResult(TemplateListInfo result)
					throws Exception {
				 
				if(result != null){
					datasource = result;
					if(fromTaskList){
						bindDataTask();
					}else{
						bindData();
					}
				}
				asyntaskIsFinished = true;
			
				hideLoading();
				finishedLoad(TAG);

			}

			@Override
			protected void runWithError(TemplateListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;
				hideLoading();
			}
		}.execute();
		
	}
	
	private void bindDataTask(){
		if (datasource != null && datasource.getTemplates() != null && datasource.getTemplates().size() > 0) {
			boolean flag = true;
			for (TemplateInfo ti : datasource.getTemplates()) {
				if (ti.getUpdate_type() != 1) {
					flag = false;
					break;
				}
			}
			if (flag) {
				finish();
			}
		}
		adapter = new ReportListAdapter(datasource);
		listView.setAdapter(adapter);
	}
	
	private void bindData() {

		if (datasource != null && datasource.getTemplates() != null && datasource.getTemplates().size() > 0) {
			boolean flag = true;
			for (TemplateInfo ti : datasource.getTemplates()) {
				if (ti.getUpdate_type() != 1) {
					flag = false;
					break;
				}
			}
			if (flag) {
				finish();
			}
		}

		if (adapter == null || pageIndex == 0) {
			adapter = new ReportListAdapter(datasource);
			if (listType == REPORT_TYPE_UNREPORT) {
				adapter.setDelegate(this);
				adapter.setHandler(this);
			}
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		if(isFromsql){
			if(fromTaskList){
				
			}else{
				totalRow = templateInfoSql.getCount();
			}
		}else{
			totalRow = datasource.getRows();
		}
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				if (isFromsql) {
					getDataFromSQL();
				} else {
					getData();
				}
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}


	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_refresh) {
			if (asyntaskIsFinished) {
				showLoading();
				pageIndex = 0;
				getData();
				asyntaskIsFinished = false;
			}
		} else if (v.getId() == R.id.btn_history) {
			IntentUtil.redirectToNext(this, TaskListActivity.class,
					PersistentKeyUtil.HISTORY_TYPE,
					PersistentKeyUtil.REPORT_TYPE_DIRECTLY);
		}
	}

  
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (type == 0) {
			if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
					&& !BizApp.getInstance().isChecking()) {
				DialogUtil.getExitAppDialog(this).show();
				return false;
			}
		}

		return super.onKeyDown(keyCode, event);
	}
}
